package com.whq.thrift.api.web.admin.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 登录通用功能类
 * @author whq-mac
 *
 */
public class LoginUtil {
	private static Log LOGGER = LogFactory.getLog(LoginUtil.class);
	
	/**
	 * 存放登录票据的session变量名
	 */
	private static final String SESSION_NAME_TICKET = "g_sessionTicket";
	
	
	/**
	 * 保存登录信息到Cookie或者Session中 
	 * @param request
	 * @param response
	 * @param ticket
	 */
	public static void saveLoginTicket(HttpServletRequest request,
			HttpServletResponse response, String ticket) {
		
		try {
			request.getSession().setAttribute(SESSION_NAME_TICKET, ticket);
		} catch(Exception ex){
			LOGGER.error("保存登录信息到session中出错,错误信息: ", ex);
		}
	}
	
	/**
	 * 将Cookie中的登录信息清空
	 * @param request
	 * @param response
	 */
	public static void clearLoginInfo(HttpServletRequest request,
			HttpServletResponse response) {
		try{
			request.getSession().removeAttribute(SESSION_NAME_TICKET);
		} catch(Exception ex) {
			LOGGER.error("清除session中的登录信息出错,错误信息: ", ex);
		}
	}
	
	/**
	 * 判断是否登录
	 * @return
	 */
	public static boolean chkIsLogin(HttpServletRequest request) {
		if (request == null) {
			return false;
		}
		
		String ticket = getLoginTicket(request);
		return StringUtils.isNotBlank(ticket);
	}
	
	/**
	 * 如果登录返回登录票据, 如果没有登录再返回null
	 * @return
	 */
	public static String getLoginTicket(HttpServletRequest request){
		try {
			if (request == null) {
				return null;
			}
			if (request.getSession() == null) {
				return null;
			}
			if (request.getSession().getAttribute(SESSION_NAME_TICKET) == null) {
				return null;
			}
			
			return request.getSession().getAttribute(SESSION_NAME_TICKET).toString();
		} catch (Exception e) {
			LOGGER.error("获取session中的登录信息出错,错误信息: ", e);
		}
		return null;
	}
	
}
